'use strict';

const Service = require('egg').Service;
const NodeRsa = require('node-rsa');
class cryptoService extends Service {
  /**
   * 生成公钥私钥
   * @return {{publicKey: String, privateKey: String}} 公钥私钥
   */
  generateKeys() {
    const key = new NodeRsa({ b: 1024 });
    const publicKey = key.exportKey('pkcs8-public-pem');
    const privateKey = key.exportKey('pkcs8-private-pem');
    return {
      publicKey,
      privateKey,
    };
  }
  /**
   * 判断公私钥是否匹配
   * @param {String} publicKey 公钥
   * @param {String} privateKey 私钥
   * @return {Boolean} 是否匹配
   */
  ifMatch(publicKey, privateKey) {
    try {
      publicKey = new NodeRsa(publicKey);
      privateKey = new NodeRsa(privateKey);
      const str = publicKey.encrypt('aa');
      return privateKey.decrypt(str) === 'aa';
    } catch (err) {
      return false;
    }
  }
  /**
   * jwt签名
   * @param {String} privateKey rsa密钥
   * @param {Object} payload 主体部分
   * @return {String} jwt字符串
   */
  jwt(privateKey, payload) {
    let header = {
      typ: 'JWT',
      alg: 'HS256',
    };
    privateKey = new NodeRsa(privateKey);
    header = Buffer.from(JSON.stringify(header), 'utf-8').toString('base64');
    payload = Buffer.from(JSON.stringify(payload), 'utf-8').toString('base64');
    const signature = privateKey.sign(`${header}.${payload}`, 'base64');
    return  `${header}.${payload}.${signature}`;
  }
}

module.exports = cryptoService;
